<template>
  <div>
    <el-dialog
      :title="'【'+val.roleName+'】权限设置'"
      :visible.sync="ConfigurePermissions"
      :width="this.$store.getters.offsetWidth"
      @close="ConfigurePermissionsClose"
      v-dialogDrag
      ref="dialog__wrapper"
      :close-on-click-modal="false"
    >
      <div class="dialog-body">
        <div class="line">
          <span class="hint">注意：加边框的权限是与菜单关联的，只有选择了该权限点，左边的菜单才会显示对应项</span>
          <ul class="dialogHeight">
            <li v-for="(item, moduleId) in checkboxList" :key="moduleId" class="customlist">
              <div v-if="item.mfmodel.length !== 0">
                <el-checkbox
                  :indeterminate="item.isIndeterminate"
                  v-model="item.checked"
                  @change="handleCheckAllChange(moduleId, $event)"
                >{{item.moduleName}}</el-checkbox>
                <!-- <div style="margin: 15px 0;"></div> -->
                <p class="checkbox_style">
                  <el-checkbox
                    v-for="(items , i) in item.mfmodel"
                    v-model="items.checked"
                    :label="items.functionName"
                    :key="i"
                    :border="i==0?true:false"
                    @change="handleCheckedCitiesChange(moduleId, items.functionId, $event)"
                  >{{items.functionName}}</el-checkbox>
                </p>
              </div>
            </li>
          </ul>
          <span
            style="width: 100%;text-align: center;margin: 20px auto 0;height: 50px;display: block;"
            class="button_dialog"
          >
            <el-button style="background-color:#4d9ce0;color:#fff" @click="submitRoleChenckd">确 定</el-button>
            <el-button @click="ConfigurePermissions = false;">取 消</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "rolecheckd",
  props: {
    Configure: {
      required: true,
    },
    roleId: {
      required: true,
    },
  },
  data() {
    return {
      isIndeterminate: true,
      checkboxList: [],
      ConfigurePermissions: false,
      id: "",
      checkdList: [],
      val: "",
    };
  },
  watch: {
    Configure(val) {
      if (this.id) {
        // this.CheckTheData();
      }
    },
    roleId(val) {
      // this.val = val;
      // this.id = val.roleId;
      // this.CheckTheData();
    },
  },
  mounted() {},
  methods: {
    openRole(val) {
      this.checkboxList = [];
      this.val = val;
      this.id = val.roleId;
      this.CheckTheData();
      //  this.$forceUpdate()
    },
    ConfigurePermissionsClose() {
      this.checkdList = [];
      this.$nextTick(() => {
        this.checkboxList.forEach((ele1) => {
          // if (ele1.mfmodel.length > 0) {
          //   ele1.mfmodel.forEach((element) => {
          //     if (element.checked) {
          //       element.checked = false;
          //     }
          //   });
          // }
          // ele1.isIndeterminate = false;
          ele1.checked = false;
        });
      });
      this.checkboxList = [];
    },
    async CheckTheData() {
      let formData = new FormData();
      let formData1 = new FormData();
      let token = window.sessionStorage.getItem("token");
      formData.append("zycmToken", token);
      formData.append("roleId", this.id);
      const { data: res } = await this.$http.post(
        "module/selectPublishModule",
        formData1
      );
      const { data: res1 } = await this.$http.post(
        "rolesFunction/selectByRole",
        formData
      );
      this.checkboxList = res.data;
      var temp01 = [];
      for (var i in res1.data) {
        temp01[res1.data[i].functionId] = true;
      }
      this.checkboxList.forEach((ele1) => {
        for (var k in ele1.mfmodel) {
          let array = ele1.mfmodel;
          if (!temp01[ele1.mfmodel[k].functionId]) {
          } else {
            ele1.mfmodel[k].checked = true;
            this.checkdList.push(ele1.mfmodel[k].functionId);
          }
        }
        let num = 0;
        for (let i = 0; i < ele1.mfmodel.length; i++) {
          if (ele1.mfmodel[i].checked) {
            num++;
          }
        }
        if (ele1.mfmodel.length == num) {
          ele1.checked = true;
        } else if (num > 0) {
          ele1.isIndeterminate = true;
        } else if (num == 0) {
          ele1.isIndeterminate = false;
          // ele1.checked = false;
        }
      });

      this.ConfigurePermissions = true;
    },
    // 全选反选的多选框
    handleCheckAllChange(index, e) {
      this.checkboxList[index].isIndeterminate = false;
      this.checkboxList[index].checked = e;

      // if (e == false) {
      //   this.checkboxList[index].isIndeterminate = false;
      // }
      var childrenArray = this.checkboxList[index].mfmodel;
      if (childrenArray) {
        for (var i = 0, len = childrenArray.length; i < len; i++) {
          if (e) {
            this.checkdList.push(childrenArray[i].functionId);
          } else {
            this.delItem(childrenArray[i].functionId, this.checkdList);
          }
          childrenArray[i].checked = "";
          this.$set(childrenArray[i], "checked", e);
        }
      }
      this.$forceUpdate();
    },
    handleCheckedCitiesChange(index, sobId, e) {
      var childrenArray = this.checkboxList[index].mfmodel;
      var tickCount = 0;
      var unTickCount = 0;
      let len = childrenArray.length;
      for (var i = 0; i < len; i++) {
        if (sobId == childrenArray[i].functionId) {
          delete childrenArray[i].checked;
          this.$set(childrenArray[i], "checked", e);
          if (e) {
            this.checkdList.push(childrenArray[i].functionId);
          } else {
            this.delItem(childrenArray[i].functionId, this.checkdList);
          }
        }
        if (childrenArray[i].checked == true) {
          tickCount++;
        }
        if (!childrenArray[i].checked) {
          unTickCount++;
        }
      }
      if (tickCount == len) {
        //二级全勾选
        this.checkboxList[index].checked = true;
        this.checkboxList[index].isIndeterminate = false;
      } else if (unTickCount == len) {
        //二级全不勾选
        this.checkboxList[index].checked = false;
        this.checkboxList[index].isIndeterminate = false;
      } else {
        this.checkboxList[index].checked = false;
        this.checkboxList[index].isIndeterminate = true; //添加一级不确定状态
      }
    },
    // 给返回的数据加是否选中的属性
    format(items) {
      return items.map((item) => {
        const result = { ...item, checked: false, isIndeterminate: false };
        if (item.checkboxList) {
          result.checkboxList = this.format(item.checkboxList);
        }
        return result;
      });
    },
    // 提交
    async submitRoleChenckd() {
      if(this.checkdList.length==0){
           this.$message({
          type: "warning",
          message: "请选择需要配置的角色权限",
        });
        return
      }
      let formData = new FormData();
      let token = window.sessionStorage.getItem("token");
      formData.append("zycmToken", token);
      formData.append("roleId", this.id);
      formData.append("functionIds", this.unique(this.checkdList));
      const { data: res } = await this.$http.post(
        "rolesFunction/savePrivilege",
        formData
      );
      if (res.result == "success") {
        this.$message({
          type: "success",
          message: res.message,
        });
      } else {
        this.$message({
          type: "error",
          message: res.message,
        });
      }
      this.ConfigurePermissions = false;
    },
    delItem(item, list) {
      //  list= list.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[])
      // 表示先获取这个元素的下标，然后从这个下标开始计算，删除长度为1的元素
      // list.splice(list.indexOf(item), 1);
      list.forEach((element) => {
        if (element == item) {
          list.splice(list.indexOf(item), 1);
        }
      });
      list.forEach((element) => {
        if (element == item) {
          list.splice(list.indexOf(item), 1);
        }
      });
    },
    unique(arr) {
      return Array.from(new Set(arr));
    },
  },
};
</script>
<style lang="stylus" scoped>
/deep/.el-dialog__header {
  background-color: #efefef;
  padding: 0;
  line-height: 50px;
  padding-left: 20px;
  color: #333;
  font-size: 16px;
}
/deep/.el-dialog__body {
  padding: 15px 20px;
}
.dialogHeight {
  height: 500px;
  width: 100%;
  overflow-y: scroll;
  overflow-x:scroll
}
.dialogHeight::-webkit-scrollbar {
  display: none;
}
.dialogHeight li {
  padding-bottom: 20px;
}
.dialogHeight li p label {
  padding: 10px 5px;
}
.hint {
  padding-bottom: 10px;
  display: block;
  color: red;
}
</style>
